﻿
namespace Timo.SqlSugar;
/// <summary>
/// 将所有数据库统一注册
/// 使用方法：http://furion.baiqian.ltd/docs/sqlsugar#1014-furion-%E9%9B%86%E6%88%90
/// </summary>
public static class SqlSugarDbContext
{
    /// <summary>
    /// 读取配置文件中的 ConnectionStrings:Sqlsugar 配置节点
    /// </summary>
    //public static readonly List<ConnectionConfig> DbConfigs = App.GetConfig<List<ConnectionConfig>>("SqlSugarSettings:DB");

    public static readonly SqlSugarScope DB = new SqlSugarScope(SqlSugarDBConfig.DbConfigs,
            db =>
            {
                SqlSugarDBConfig.DbConfigs.ForEach(it =>
                {
                    var sqlsugarScope = db.GetConnectionScope(it.ConfigId);//获取当前库
                    AopSetting(sqlsugarScope);//AOP配置
                });
                //如果数据库不存在则创建数据库
                //db.DbMaintenance.CreateDatabase();
                //从数据库生成实体model
                //db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\xxx\models", "Models");
                //从实体类创建数据库表。可传递表参数以创建指定表，typeof(your_model)
                //db.CodeFirst.InitTables();
            });

    public static void AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<ISqlSugarClient>(DB);
    }

    /// <summary>
    /// Aop设置
    /// </summary>
    /// <param name="db"></param>
    public static void AopSetting(SqlSugarScopeProvider db)
    {
        var config = db.CurrentConnectionConfig;

        // 设置超时时间，秒
        db.Ado.CommandTimeOut = 60;

        // 打印SQL语句
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            if (App.HostEnvironment.IsDevelopment())
            {
                if (sql.StartsWith("SELECT"))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    WriteSqlLog($"查询{config.ConfigId}库操作");
                }
                if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    WriteSqlLog($"修改{config.ConfigId}库操作");
                }
                if (sql.StartsWith("DELETE"))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    WriteSqlLog($"删除{config.ConfigId}库操作");
                }
                Console.WriteLine(UtilMethods.GetSqlString(config.DbType, sql, pars));
                WriteSqlLog($"{config.ConfigId}库操作结束");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine();
            }            
        };
        //异常
        db.Aop.OnError = (ex) =>
        {
            if (App.HostEnvironment.IsDevelopment()) {
                if (ex.Parametres == null) return;
                Console.ForegroundColor = ConsoleColor.Red;
                var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
                WriteSqlLog($"{config.ConfigId}库操作异常");
                Console.WriteLine(UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
                Console.ForegroundColor = ConsoleColor.White;
            }            
        };
        //插入和更新过滤器
        db.Aop.DataExecuting = (oldValue, entityInfo) =>
        {
            // 新增操作
            //if (entityInfo.OperationType == DataFilterType.InsertByObject)
            //{
            //    // 主键(long类型)且没有值的---赋值雪花Id
            //    if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
            //    {
            //        var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
            //        if (id == null || (long)id == 0)
            //            entityInfo.SetValue(CommonUtils.GetSingleId());
            //    }
            //    if (entityInfo.PropertyName == nameof(BaseEntity.CreateTime))
            //        entityInfo.SetValue(DateTime.Now);

            //    if (App.User != null)
            //    {
            //        //创建人和创建机构ID
            //        if (entityInfo.PropertyName == nameof(BaseEntity.CreateUserId))
            //            entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
            //        if (entityInfo.PropertyName == nameof(BaseEntity.CreateUser))
            //            entityInfo.SetValue(App.User?.FindFirst(ClaimConst.Account)?.Value);
            //        if (entityInfo.PropertyName == nameof(DataEntityBase.CreateOrgId))
            //            entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
            //    }
            //}
            //// 更新操作
            //if (entityInfo.OperationType == DataFilterType.UpdateByObject)
            //{
            //    //更新时间
            //    if (entityInfo.PropertyName == nameof(BaseEntity.UpdateTime))
            //        entityInfo.SetValue(DateTime.Now);
            //    //更新人
            //    if (App.User != null)
            //    {
            //        if (entityInfo.PropertyName == nameof(BaseEntity.UpdateUserId))
            //            entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
            //        if (entityInfo.PropertyName == nameof(BaseEntity.UpdateUser))
            //            entityInfo.SetValue(App.User?.FindFirst(ClaimConst.Account)?.Value);
            //    }
            //}
        };

        //查询数据转换
        db.Aop.DataExecuted = (value, entity) =>
        {
        };
    }
    private static void WriteSqlLog(string msg)
    {
        Console.WriteLine($"=============={msg}==============");
    }
}
